package com.lite.haru.alarmpolice.activity;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.KJBitmap;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.bitmap.BitmapCallBack;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.widget.ScaleImageView;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.VideoView;

import com.lite.haru.R;
import com.lite.haru.constant.Constant;
import com.lite.haru.constant.PoliceApplication;

public class AlarmInfoDetailAty extends KJActivity implements
		MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener,
		OnPreparedListener, OnBufferingUpdateListener, OnErrorListener {
	private KJBitmap kjb;
	private KJHttp kjh;
	private Uri mUri;
	private int mPositionWhenPaused = -1;
	private Dialog dialog;
	private PoliceApplication mApp;
	private MediaPlayer player;

	private MediaController mMediaController;
	int alarm_id, police_id;// 报警信息的业务id police_id当前app登录的警务人员的id
	String username, phone, address, contactperson, contactpersonphone,
			alarmtype, alarmwork, disaster, grade, formatted_address,
			sematic_description, flag;//
	double latitude, longitude;
	@BindView(id = R.id.info_flag, click = true)
	private TextView info_flag;
	@BindView(id = R.id.info_username)
	private TextView info_username;
	@BindView(id = R.id.info_phone, click = true)
	private TextView info_phone;
	@BindView(id = R.id.info_address)
	private TextView info_address;
	@BindView(id = R.id.info_contactperson)
	private TextView info_contactperson;
	@BindView(id = R.id.info_contactpersonphone, click = true)
	private TextView info_contactpersonphone;
	@BindView(id = R.id.info_alarmtype)
	private TextView info_alarmtype;
	@BindView(id = R.id.info_disaster)
	private TextView info_disaster;
	@BindView(id = R.id.info_grade)
	private TextView info_grade;
	@BindView(id = R.id.info_formatted_address)
	private TextView info_formatted_address;
	@BindView(id = R.id.info_my_loc)
	private TextView info_my_loc;

	@BindView(id = R.id.info_sematic_description)
	private TextView info_sematic_description;

	@BindView(id = R.id.info_msg)
	private TextView info_msg;
	@BindView(id = R.id.info_img, click = true)
	private ScaleImageView info_img;
	@BindView(id = R.id.info_record_start, click = true)
	private Button info_record_start;
	@BindView(id = R.id.info_record_stop, click = true)
	private Button info_record_stop;
	@BindView(id = R.id.status)
	private TextView status;

	@BindView(id = R.id.buffervalue)
	private TextView buffervalue;

	private VideoView info_video;
	@BindView(id = R.id.open_map, click = true)
	private TextView open_map;
	@BindView(id = R.id.hide_text, click = true)
	private TextView hide_text;
	@BindView(id = R.id.backHome, click = true)
	private TextView backHome;
	@BindView(id = R.id.show_detail)
	private ScrollView show_detail;

	@BindView(id = R.id.progressBar)
	private ProgressBar progressBar;
	@BindView(id = R.id.tv_progressBar)
	private TextView tv_progressBar;

	@BindView(id = R.id.record_block)
	private LinearLayout record_block;

	@Override
	public void setRootView() {
		setContentView(R.layout.aty_alarm_info_detail);
	}

	@Override
	public void initData() {
		kjb = new KJBitmap();

		kjh = new KJHttp();
		mApp = (PoliceApplication) getApplication();
		police_id = mApp.police_id;
		Bundle bundle = this.getIntent().getExtras();

		alarm_id = bundle.getInt("id");
		username = bundle.getString("username");
		phone = bundle.getString("phone");
		address = bundle.getString("address");
		contactperson = bundle.getString("contactperson");
		contactpersonphone = bundle.getString("contactpersonphone");
		alarmtype = bundle.getString("alarmtype");
		alarmwork = bundle.getString("alarmwork");
		disaster = bundle.getString("disaster");
		grade = bundle.getString("grade");
		latitude = bundle.getDouble("latitude");
		longitude = bundle.getDouble("longitude");
		formatted_address = bundle.getString("formatted_address");
		sematic_description = bundle.getString("sematic_description");
		flag = bundle.getString("flag");

		super.initData();
	}

	@Override
	public void initWidget() {
		info_video = (VideoView) findViewById(R.id.info_video);
		status.setText("加载中");
		player = new MediaPlayer();
		player.setOnCompletionListener(this);
		player.setOnErrorListener(this);
		player.setOnPreparedListener(this);
		player.setOnBufferingUpdateListener(this);
		status.setText("Player created");

		setTVInfo();
		super.initWidget();
	}

	@Override
	public void widgetClick(View v) {

		switch (v.getId()) {
		case R.id.info_flag:
			Alarm();
			break;

		case R.id.info_record_start:
			player.start();
			status.setText("正在播放录音");
			info_record_stop.setEnabled(true);
			info_record_start.setEnabled(false);
			break;
		case R.id.info_record_stop:
			player.pause();
			status.setText("继续播放录音");
			info_record_start.setEnabled(true);
			info_record_stop.setEnabled(false);
			break;

		case R.id.info_phone:
			Uri uri = Uri.parse("tel:" + phone);
			Intent intent = new Intent(Intent.ACTION_DIAL, uri);
			startActivity(intent);
			break;

		case R.id.info_contactpersonphone:
			Uri uri1 = Uri.parse("tel:" + contactpersonphone);
			Intent intent1 = new Intent(Intent.ACTION_DIAL, uri1);
			startActivity(intent1);
			break;
		case R.id.open_map:
			openMap();
			break;
		case R.id.hide_text:

			if (hide_text.getText().toString().equals("显示详情")) {
				displayText();
			} else {
				hiddenText();
			}
			break;

		case R.id.backHome:
			AlarmInfoDetailAty.this.finish();
			break;
		default:
			break;
		}
		super.widgetClick(v);
	}

	public void setTVInfo() {

		if (alarmtype.equals("photo")) {
			alarmtype = "图片";
			info_img.setVisibility(View.VISIBLE);
			info_img.setCanDoubleClick(true);
			kjb.display(info_img, Constant.url + "/" + alarmwork,
					new BitmapCallBack() {
						@Override
						public void onPreLoad() {
							super.onPreLoad();
							progressBar.setVisibility(View.VISIBLE);
							tv_progressBar.setVisibility(View.VISIBLE);
						}

						@Override
						public void onFailure(Exception e) {
							super.onFailure(e);
							ViewInject.toast("图片加载失败！");
						}

						@Override
						public void onFinish() {
							super.onFinish();
							progressBar.setVisibility(View.GONE);
							tv_progressBar.setVisibility(View.GONE);
						}
					});
		} else if (alarmtype.equals("record")) {
			alarmtype = "录音";
			record_block.setVisibility(View.VISIBLE);
			try {

				String url = "http://www.lit402.top:8080/AlarmService/"
						+ alarmwork;
				player.setDataSource(url);
				status.setText("正在缓冲录音");
				player.prepareAsync();
				info_record_start.setEnabled(false);
			} catch (Exception e) {
				e.printStackTrace();
				Log.d("xhj", e.getCause().getLocalizedMessage() + ":");
			}
		} else if (alarmtype.equals("video")) {
			alarmtype = "视频";
			info_video.setVisibility(View.VISIBLE);
			mUri = Uri.parse(Constant.url + "/" + alarmwork);
			mMediaController = new MediaController(this);
			info_video.start();
			info_video.setMediaController(mMediaController);

		} else {
			alarmtype = "短信";
			// info_msg.setVisibility(View.VISIBLE);
		}

		if (flag == null) {
			flag = "接警";
		}
		info_flag.setText(flag);
		info_username.setText("报警人姓名：" + username);
		info_phone.setText("报警人电话：" + phone + "  <-点击拨打");
		info_address.setText("报警人家庭地址：" + address);
		info_contactperson.setText("紧急联系人:" + contactperson);
		info_contactpersonphone.setText("紧急联系人电话：" + contactpersonphone
				+ "  <-点击拨打");
		info_alarmtype.setText("报警方式：" + alarmtype);
		info_disaster.setText("报警信息：" + disaster);
		info_grade.setText("报警等级：" + grade);
		info_formatted_address.setText("报警人位置：" + formatted_address + " 附近");
		info_sematic_description.setText("参考位置(报警人为参照物)" + sematic_description);
		// info_my_loc.setText("我的位置");
		// info_msg.setText("短信内容为:" + alarmwork);

	}

	/**
	 * 接警处理
	 */
	private void Alarm() {
		if (flag.equals("接警")) {
			showTips(aty);
		} else {
			info_flag.setClickable(false);
		}
	}

	/**
	 * 打开地图，查看路径
	 */

	public void openMap() {

		Bundle bundle = new Bundle();
		bundle.putDouble("mLatitude", latitude);
		bundle.putDouble("mLongitude", longitude);
		bundle.putString("mFormatted_address", formatted_address);
		Intent intent = new Intent(getApplicationContext(),
				AlarmRoutePlanAty.class);
		intent.putExtras(bundle);
		startActivity(intent);

	}

	// 隐藏详情

	public void hiddenText() {
		show_detail.setVisibility(View.GONE);

		if (alarmtype.equals("图片")) {
			info_img.setVisibility(View.VISIBLE);
		} else if (alarmtype.equals("录音")) {
			record_block.setVisibility(View.VISIBLE);
		} else if (alarmtype.equals("视频")) {
			info_video.setVisibility(View.VISIBLE);
		}

		hide_text.setText("显示详情");
	}

	// 显示详情

	public void displayText() {
		show_detail.setVisibility(View.VISIBLE);
		if (alarmtype.equals("图片")) {
			info_img.setVisibility(View.GONE);
		} else if (alarmtype.equals("录音")) {
			record_block.setVisibility(View.GONE);
		} else if (alarmtype.equals("视频")) {
			info_video.setVisibility(View.GONE);
		}

		hide_text.setText("隐藏详情");
	}

	/**
	 * 推出应用提示
	 * 
	 * @param context
	 */
	private void showTips(Context context) {

		LayoutInflater inflater = LayoutInflater.from(context);
		// 绑定 布局
		View layout = inflater.inflate(R.layout.my_alert_dialog, null);

		dialog = new AlertDialog.Builder(aty).create();
		dialog.setCancelable(false);
		dialog.show();
		dialog.getWindow().setContentView(layout);
		TextView dialog_tip = (TextView) layout.findViewById(R.id.dialog_tip);
		dialog_tip.setText("确认接警");

		TextView btn_ok = (TextView) layout.findViewById(R.id.btn_ok);
		TextView btn_cancel = (TextView) layout.findViewById(R.id.btn_cancel);
		btn_ok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				String url = Constant.url + "/UpdateAlarmInfoAction";
				HttpParams params = new HttpParams();
				params.put("param0", "update_statement");
				params.put("alarm_id", alarm_id);
				params.put("police_id", police_id);
				kjh.post(url, params, new HttpCallBack() {
					@Override
					public void onSuccess(String t) {
						if (t.equals("success")) {
							ViewInject.toast("已接警，请尽快到达现场");
							AlarmInfoDetailAty.this.finish();
						} else if (t.equals("failed")) {
							ViewInject.toast("接警失败，请重新尝试");
						}
						super.onSuccess(t);
					}

					@Override
					public void onFailure(int errorNo, String strMsg) {
						super.onFailure(errorNo, strMsg);
					}
				});
			}
		});

		btn_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

	}

	@Override
	protected void onDestroy() {
		try {
			dialog.dismiss();
		} catch (Exception e) {
			
		}
		super.onDestroy();
	}

	//

	// 开始
	public void onStart() {
		// Play Video
		info_video.setVideoURI(mUri);
		info_video.start();

		super.onStart();
	}

	// 暂停
	public void onPause() {
		// Stop video when the activity is pause.
		mPositionWhenPaused = info_video.getCurrentPosition();
		info_video.stopPlayback();
		Log.d("xhj", "OnStop: mPositionWhenPaused = " + mPositionWhenPaused);
		Log.d("xhj", "OnStop: getDuration  = " + info_video.getDuration());

		super.onPause();
	}

	public void onResume() {
		// Resume video player
		if (mPositionWhenPaused >= 0) {
			info_video.seekTo(mPositionWhenPaused);
			mPositionWhenPaused = -1;
		}
		super.onResume();
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		// player.start();
		status.setText("点击播放");
		info_record_start.setEnabled(true);
		info_record_stop.setEnabled(false);

	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		status.setText("此录音播放错误");
		String text = "";
		switch (what) {
		case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
			text = "MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK " + extra;
			break;
		case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
			text = "MEDIA_ERROR_SERVER_DIED " + extra;
			break;
		case MediaPlayer.MEDIA_ERROR_UNKNOWN:
			text = "MEDIA_ERROR_UNKNOWN " + extra;
			break;
		default:
			break;
		}
		status.setText(text);
		return false;
	}

	@Override
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		buffervalue.setText(percent + "%");
		Log.i("xhj", "" + percent);
	}

	@Override
	public void onError(MediaRecorder mr, int what, int extra) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		status.setText("录音播放完毕");
		info_record_start.setEnabled(true);
		info_record_stop.setEnabled(false);
	}

}
